<template>
    <el-dialog v-model="editRoleVisible" title="编辑角色" @close="handleClose" draggable>
        <el-form ref="formRef" :model="editRoleForm" label-width="auto">
            <el-form-item label="角色名称" prop="name">
                <el-input v-model="editRoleForm.name" clearable />
            </el-form-item>
            <el-form-item label="角色权限值" prop="roleKey">
                <el-input v-model="editRoleForm.roleKey" clearable />
            </el-form-item>
            <el-form-item label="显示顺序" prop="seqNo">
                <el-input v-model="editRoleForm.seqNo" clearable />
            </el-form-item>
            <el-form-item label="角色状态" prop="status">
                <el-radio-group v-model="editRoleForm.status">
                    <el-radio :value="1">启用</el-radio>
                    <el-radio :value="0">禁用</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="备注" prop="remark">
                <el-input v-model="editRoleForm.remark" type="textarea" />
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="handleClose">取消</el-button>
                <el-button type="primary" @click="submitForm">确认</el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup>
import { ref, reactive, watch, inject } from 'vue'
import { editRole } from '@/api/system/role'
import { useRoute, useRouter } from 'vue-router'

const route = useRoute()
const router = useRouter()

const formRef = ref(null)

const { editRoleVisible, selectedRow } = inject('editRole')

const editRoleForm = reactive({
    id: undefined,
    name: undefined,
    roleKey: undefined,
    seqNo: undefined,
    status: undefined,
    remark: undefined
})

watch(
    () => selectedRow.value,
    (newValue) => {
        if (newValue) {
            Object.assign(editRoleForm, newValue)
        }
    },
    {
        // 立即以当前路由的值为触发条件
        immediate: true
    }
)
/**
 * 重置表单
 * @param formEl 表单的ref
 */
function resetForm(formEl) {
    if (!formEl) return
}
/**
 * 提交表单
 */
function submitForm() {
    editRoleVisible.value = false
    editRole(editRoleForm)
    resetForm(formRef)
    // 刷新表格
    const { query, path } = route
    router.replace({ path: '/redirect' + path, query: query })
}

// 重置 editRoleForm 的函数
const resetEditRoleForm = () => {
    Object.keys(editRoleForm).forEach((key) => {
        editRoleForm[key] = undefined
    })
}
// 处理对话框关闭事件
function handleClose() {
    resetForm(formRef)
    resetEditRoleForm()
    editRoleVisible.value = false
}
</script>

<style lang="scss" scoped></style>
